/**
 * Created by Administrator on 2015/11/19.
 */
var conn = require('../util/conn');
var Q = require('q');
/**
 * department.parentId
 * callback(data)
 * data is database query result
 * @parentId
 * @callback
 */
var getDepartments = function(parentId,callback){
    var connection = conn.getConnection();
    connection.connect();
    var sql = '';
    if(!parentId){//parentId === undefined
        sql = 'select * from department where parentId is null';
    }
    else{
        sql = 'select * from department where parentId = ' + parentId;
    }
    var query = connection.query(sql,function(err,rows,fields){
        if(err) throw err;
        var retObj = [];
        for(var i in rows){
            var obj = { id:rows[i].id,
                        text:rows[i].name};
            getDepartments(rows[i].departmentId,function(data){
                if(data.length !== 0){
                    obj.children = data;
                }
                retObj.push(obj);
            });
            callback(retObj);
        }
        //callback(rows);
    })
};
/**
 * id = department.id
 * callback({
 *  id:
 *  name:
 *  parentId:
 * })
 * @param id
 * @param callback
 */
var getDepartment = function(id,callback){
    var connection = conn.getConnection();
    connection.connect();
    if(typeof id === 'string'){
        id = parseInt(id);
    }else if(typeof id !== 'number'){
        throw Error('id must be a number');
    }
    var query = connection.query('select * from department where id = ?',[id],function(err,rows,fields){
        if(err) throw err;
//        console.log(typeof rows);
//        console.log('++++++++++++++');
//        console.log(rows[0]);
        callback(rows[0]);
    });
    console.log(query.sql);
    connection.end();
};
//getDepartment(1);
var q_getDepartment = Q.denodeify(getDepartment);
var q_getDepartments = Q.denodeify(getDepartments);
var promise = q_getDepartment(1);
promise.then(function(data){
    if(typeof data === 'object' && data.id !== undefined){
        var retObj = {
            id:data.id,
            text:data.name
        };
        return q_getDepartments(data.id)
            .then(function(rows){
                var childeren = [];
                for(var i in rows){
                    var temp = {
                        id:row[0].id,
                        text:row[0].name
                    }
                    childeren.push(temp);
                }
                retObj.children = childeren;
            });
    }
}).then();
//var promise1 = q_getDepartments(2);
//promise1.then(console.log,console.error);
var getUsers = function(page,rows,callback){

    var retObj = {};
    var connection = conn.getConnection();
    connection.connect();
    if(!page || !rows){
        page = 1;
        rows = 10;
    }
    else{
        page = parseInt(page);
        rows = parseInt(rows);
    }
    var start = (page-1)*rows;
    connection.query('select count(*) as result from user',function(err,rows,fields){
        retObj.result = rows[0].result;//获取总行数
    });
    var query = connection.query('select * from user limit ?,?',[start,rows], function(err, rows, fields) {
        if (err) throw err;

        datas = [];
        for(var row in rows){
            var node = {
                id:rows[row].id,
                name:rows[row].name
            }
            datas[row] = node;
        }
        retObj.rows = datas;
        callback(retObj);
    });
    console.log(query.sql);
    connection.end();
}

var deleteUser = function(ids,callback){
    var connection = conn.getConnection();
    connection.connect();
    //connection.query('INSERT INTO user values(null,?,null)',)
    var idsStr = '';
    for(var i in ids){
        idsStr = idsStr +',' + ids[i];
    }
    idsStr = idsStr.replace(/(^,*)/g,'');
    idsStr = '( ' + idsStr + ' )';
    var query = connection.query('DELETE FROM user WHERE id in'+idsStr,function(err,result){
        if(err) throw  err;
        console.log('delete ' + result.affectedRows + ' rows');
        callback({affectedRows:result.affectedRows});
    });
    console.log(query.sql);
    connection.end();
}
/**
 *
 * @param user
 * @param callback
 */
var editUser = function(user,callback){
    var connection = conn.getConnection();
    connection.connect();
//    var query = connection.query('UPDATE user SET name = ?,departmentId = ? where id = ?',[user.name,user.departmentId,user.id],function(err,result){
    var query = connection.query('UPDATE user SET name = ? where id = ?',[user.name,user.id],function(err,result){
        if(err) throw err;
        console.log(result.changedRows);
        callback({changedRows:result.changedRows});
    });
    console.log(query.sql);
    connection.end();
}
/**
 * user
 * {
 *      id:null,
 *      name:'xx',
 *      departmentId:2
 * }
 * addUser(user,function(data){
 *      console.log(data);
 *      xx.send(data);
 * })
 * @param user
 */
var addUser = function(user,callback){
    //var retObj = {};
    var connection = conn.getConnection();
    connection.connect();
    var query = connection.query('INSERT INTO user SET ?',user,function(err,result){
        if (err) throw err;

        console.log(result.insertId);
        callback({insertId:result.insertId});
    });
    console.log(query.sql);
    connection.end();
}
//module.exports = {
//    list:getDepartments,
//    add:addDepartment,
//    edit:editDepartment,
//    delete:deleteDepartment
//};